home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / ptv1n1.arc / L6.C < prev    next >
Text File  |  1990-06-08  |  2KB  |  61 lines

  1. /*
  2.  * *** Listing 6 ***
  3.  *
  4.  * Program to calculate the 16-bit checksum of the stream of bytes
  5.  * from the specified file.  Buffers the bytes internally, rather
  6.  * than letting C or DOS do the work, with the time-critical 
  7.  * portion of the code written in optimized assembler.
  8.  */
  9. #include <stdio.h>
  10. #include <fcntl.h>
  11. #include <alloc.h>   /* alloc.h for Turbo C 2.0,
  12.                         malloc.h for Microsoft C 5.0 */
  13.  
  14. #define BUFFER_SIZE  0x8000   /* 32Kb data buffer */
  15.  
  16. main(int argc, char *argv[]) {
  17.    int Handle;
  18.    unsigned int Checksum;
  19.    unsigned char *WorkingBuffer;
  20.    int WorkingLength;
  21.  
  22.    if ( argc != 2 ) {
  23.       printf("usage: checksum filename\n");
  24.       exit(1);
  25.    }
  26.  
  27.    if ( (Handle = open(argv[1], O_RDONLY | O_BINARY)) == -1 ) {
  28.       printf("Can't open file: %s\n", argv[1]);
  29.       exit(1);
  30.    }
  31.  
  32.    /* Get memory in which to buffer the data */
  33.    if ( (WorkingBuffer = malloc(BUFFER_SIZE)) == NULL ) {
  34.       printf("Can't get enough memory\n");
  35.       exit(1);
  36.    }
  37.  
  38.    /* Initialize the checksum accumulator */
  39.    Checksum = 0;
  40.  
  41.    /* Process the file in 32Kb chunks */
  42.    do {
  43.       if ( (WorkingLength = read(Handle, WorkingBuffer,
  44.             BUFFER_SIZE)) == -1 ) {
  45.          printf("Error reading file %s\n", argv[1]);
  46.          exit(1);
  47.       }
  48.       /* Checksum this chunk if there's anything in it */
  49.       if ( WorkingLength ) {
  50.          ChecksumChunk(WorkingBuffer, WorkingLength, &Checksum);
  51.       }
  52.    } while ( WorkingLength );
  53.  
  54.    /* Report the result */
  55.    printf("The checksum is: %u\n", Checksum);
  56.  
  57.    exit(0);
  58. }
  59.  
  60.  
  61.